<?php
namespace Cyfy\Modules\Book;

use \Cyfy\Modules\Users\Current;
use \Cyfy\Modules\Users\User;


/**
 * Guest Book module.
 *
 * This module include_onces an ordinary Guest Book.
 * Users can insert entries, if they have permission.
 * The URL is /book by default, you can change it by modifying filesystem.xml and this class constants.
 * When changing path, the module must be set to DISABLED!!! Otherwise it won't change the filesystem.
 */
class Module extends \Cyfy\Module
{
    /**
     * Default entries on page, can be changed from administration.
     */
    const ON_PAGE_DEFAULT = 10;
    
    /**
     * Maximum characters shown in the block LATEST ENTRY.
     */
    const BLOCK_LIMIT = 255;
    
    /**
     * Path to the Guest Book. If you want to change it, disable the module at first, then edit this constant and entries in filesystem.xml.
     */
    const BOOK_PATH = 'book/';
    
    /**
     * Method handling AJAX calls.
     *
     * Available methods are:
     * <ul>
     *    <li>'entries' - returns list of entries as HTML, starting on page 1</li>
     * </ul>
     *
     * @param string Called method name.
     * @return mixed AJAX callback result or FALSE.
     */
    static public function ajax($name)
    {
        switch($name)
        {
            case 'entries':
                return self :: ajaxEntries();
                
            default:
                return false;
        }
    }
    
    
    /**
     * Administration method.
     *
     * Available methods are:
     * <ul>
     *    <li>'settings' - settings for Guest book</li>
     * </ul>
     *
     * @param string Called method name.
     * @return mixed Callback result or FALSE.
     */
    static public function administration($name = '')
	{
        switch($name){
            case 'settings':
                $form = new Forms\Settings();
                $form -> setDataFromConstants(array('perPage', 'showTitle'));
                return $form -> show();
            
            case '':
                return array(
                    'settings' => array('name' => self :: t(400) , 'description' => self :: t(410), 'permission'=> 'administration')
                );
                
            default:
                return false;
        }
	}
    
    /**
     * Blocks
     *
     * Available blocks are:
     * <ul>
     *    <li>'lastEntry' - last entry in guestbook, returned as HTML</li>
     * </ul>
     *
     * @param string Block name
     * @return mixed
     */
    static public function blocks($name='')
    {
        switch($name){
            case '':
                return array('lastEntry' => self :: t(40));
            case 'lastEntry';
                return self :: lastEntry();
            default:
                return false;
        }        
    }
    
    /**    
     * Returns content, which corresponds with parameter $name.
     *
     * Available values are:
     * <ul>
     *    <li>'main' - the main page of book</li>
     *    <li>'entry' - one entry</li>
     * </ul>
     *
     * @param string Name of the content to get.
     * @return string Returned content.
     */
    static public function get($name)
    {
        $output = '<h2>' . self :: t(10) . '</h2>';
        switch($name)
        {
            case 'main':
                \Cyfy\Template :: setTitle(self :: t(10));
                return $output . self::bookAll();
            
            case 'entry':
                \Cyfy\Template :: setTitle(self :: t(250));
                return $output . self::bookEntry(\Cyfy\Cyfy ::  arg(1));
            
            default:
                return '';
        }    
    }
    
    /**
     * Returns all entries.
     * @return string Book entries.
     */
    static private function bookAll()
    {
        // CSS
        \Cyfy\Cyfy ::  CSS(\Cyfy\Cyfy ::  getSourcePath('Cyfy/Modules/Book/book.css'));
        
        // FORM
        if(\Cyfy\Cyfy ::  permission('Book', 'add new'))
        {
            $form = new Forms\NewEntry();
            $c = new  \Cyfy\Modules\Objects\Collapsible();
            $c -> setClass('bookNewEntryCollapsibleForm');
            $c -> setData(self :: t(100), $form -> show(), true);
            
            $output = $c -> show();            
        }
        // ENTRIES
        $pager = new \Cyfy\Modules\DibiPager\DibiPager('guestbook', self :: constant('perPage'));		
        $pager -> ajaxCall('Book','entries', '#guestBook');
        
        $output .= '<div id=\'guestBook\'>' . self :: ajaxEntries() . '</div>';
        $output .= $pager -> pager('SELECT count([eid]) FROM [:cyfy:Book]');
        return $output;
    }
    
    /**
     * Returns one entry.
     * @param int EntryID.
     * @return string Book entry.
     */
    static private function bookEntry($eid)
    {
        $e = \dibi :: query('SELECT * FROM [:cyfy:Book] WHERE eid = %i', $eid) -> fetch();
        
        // if some found
        if($e)
        {
            // edit?
            if(\Cyfy\Cyfy ::  permission('Book', 'edit all') || (\Cyfy\Cyfy ::  permission('Book', 'edit own') && $e['uid'] == User :: $uid))
            {
                $form = new Forms\EditEntry();
                $e['text'] = strip_tags($e['text']);
                $form -> setData($e);
                $form -> setTemp('eid', $eid);
                
                $output = '<h3>' . self :: t(250) . '</h3>';
                $output .= $form -> show();
                return $output;
            }
            else
            {
                return \Cyfy\Cyfy ::  noPermission(true);
            }
        }
        
        \Cyfy\Message :: set( self :: t(30) , \Cyfy\Message::ERROR);
        return '';        
    }
  
    /**
     * Returns the last entry
     * @return string Book entry.
     */
    static private function lastEntry()
    {
        // result of book and users
        $result = \dibi :: query('SELECT [:cyfy:Book].[title],[:cyfy:Book].[text],[:cyfy:Book].[eid],[:cyfy:Book].[time],[:cyfy:Book].[eid],[:cyfy:Book].[name],[:cyfy:Users-users].[name] as fullName FROM [:cyfy:Book] LEFT JOIN [:cyfy:Users-users] USING ([uid]) ORDER BY [:cyfy:Book].[time] DESC LIMIT 1');

        // nothing found
        if(count($result) == 0)
        {
            $output = '<h3>' . self :: t(10) . '</h3>';
            $output .= '<p>' . self :: t(20) . '</p>';
            return $output;
        }
        
        $e = $result -> fetch();
        // user & name
        $u = ($e['fullName']) ?  $e['fullName'] : $e['name'];
        
        // time
        $t = \Cyfy\Modules\Locale\Locale :: getTime($e['time']);
        
        // text
        $e['text'] = strip_tags(substr($e['text'], 0, self :: BLOCK_LIMIT)) . '...';
       
        // title, if enabled
        if(self :: constant('showTitle')){
            $title = "<p class=\"title\">{$e["title"]}</strong></p>";
        }else{
            $title = '';
        }
        
        $output = '<h3><a href=\'' . \Cyfy\Cyfy ::  getPath(self :: BOOK_PATH) . '\'>' . self :: t(40) . '</a></h3>';
        $output .= <<<ENTRY
$title
<p class="user">{$u}</strong></p>
<p class="time">{$t}</strong></p>
<p>{$e["text"]}</p>
ENTRY;
        
        return $output;        
    }
  
    /**
     * Returns all entries. This method is used by ordinary GET as well as by AJAX callback.
     * @return string Book entries.
     */
    static private function ajaxEntries()
    {
        // If delete
        if(is_numeric($_POST['deleteEntry'])){
            self :: deleteEntry($_POST['deleteEntry']);
        }

        // pager declaration and ajax
        $pager = new \Cyfy\Modules\DibiPager\DibiPager('guestbook', self :: constant('perPage'));		
        $pager -> ajaxCall('Book','entries', '#guestBook');
        
        
        // pager query
        $result = $pager -> query('SELECT [:cyfy:Book].[title],[:cyfy:Book].[text],[:cyfy:Book].[eid],[:cyfy:Book].[time],[:cyfy:Book].[eid],[:cyfy:Book].[name],[:cyfy:Users-users].[name] as fullName FROM [:cyfy:Book] LEFT JOIN [:cyfy:Users-users] USING ([uid]) ORDER BY [:cyfy:Book].[time] DESC');

		// if no results, exit with no entries found
		if(count($result) == 0){
			return \Cyfy\Message :: get( self :: t(20), \Cyfy\Message::WARNING);
		}
		 
        // odd and even setting for nice colours
        $evenOdd = 'odd'; 
        
        // entries itetator
		foreach($result as $e)
		{
            // odd & even settings
            $evenOdd = ($evenOdd == 'even') ? 'odd' : 'even';
            
            // name and admin settings
            $name = ($e['fullName']) ?  $e['fullName'] : $e['name'];
            
            // time format
            $time = \Cyfy\Modules\Locale\Locale :: getTime($e['time']);
            
            // delete and edit
            $edit = '';
            if(Current :: $uid != 0){
                if((\Cyfy\Cyfy ::  permission('Book', 'edit own') && $e['uid'] == Current :: $uid) || \Cyfy\Cyfy ::  permission('Book', 'edit all')){
                    $edit .= "        <input type=\"submit\" class=\"button-normal\" value=\"" . self :: t(210) . "\" onclick=\"Cyfy.redirectTo('book/{$e["eid"]}')\">\n";
                    $edit .= "        <input type=\"submit\" class=\"button-warning\" value=\"" . self :: t(220) . "\" onclick=\"if(confirm('" . self :: t(230) . "')){ Cyfy.ajax('Book', 'entries', '#guestBook', 'deleteEntry={$e["eid"]}') }\">\n";
                }
            }
        
            // title
            $title = '';
            if(self :: constant('showTitle'))
            {
                $title = "  <h2 class=\"title\">{$e["title"]}</h2> ";
            }

            // building a entry... templates oneday??
$output .= <<<ENTRY
<div class="bookEntry {$evenOdd}"> 
    <div class="text"> 
        {$title}
        <p class="bookText">{$e["text"]}</p> 
    </div> 
    <div class="date"> 
        <p class="bookTime">{$time}</p> 
        <p class="bookUser">{$name}</p> 
    </div> 
    <div class="edit"> 
{$edit}
    </div> 
</div>             
ENTRY;
        }
        return $output;
    }
  
    /**
     * Deletes an entry.
     *
     * @param int EntryID
     * @return bool TRUE, if operation successful, FALSE otherwise.
     */
    static private function deleteEntry($eid)
    {
        $result = \dibi :: query('SELECT [title], [uid] FROM [:cyfy:Book] WHERE eid = %i', $eid);
    
        if(count($result) == 0){
			\Cyfy\Message :: set( self :: t(30), \Cyfy\Message::ERROR);
            return false;
		}
        
        // Entry
        $e = $result -> fetch();
    
        if(Current :: $uid != 0)
        {
            // permission to delete?
            if((\Cyfy\Cyfy ::  permission('Book', 'edit own') && $e['uid'] == Current :: $uid) || \Cyfy\Cyfy ::  permission('Book', 'edit all'))
            {
                \dibi :: query('DELETE FROM [:cyfy:Book] WHERE eid = %i', $eid);
                \Cyfy\Message :: set(self :: t(231, array($e['title'])));
                return true;
            }
        }
        
        \Cyfy\Cyfy ::  noPermission();
        return false;
    }
}
